package com.cb.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cb.msmservice.service.MsmService;
import com.cb.servicebase.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author cb
 * @version 1.0
 * @date 2020/6/27 11:04
 */
@Service
public class MsmServiceImpl implements MsmService {

    private final RedisTemplate<String,String> redisTemplate;

    @Autowired
    public MsmServiceImpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean send(Map<String, Object> param, String phone) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }

        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI4GFK7TwdFhpc4iE3dgv9", "ymAOvSOPejYo4mOpkofofbrOGrJbil");
        IAcsClient client = new DefaultAcsClient(profile);

        // 设置相关固定参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 设置发送相关的参数
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "我的ce谷粒在线教育网站");  // 阿里云中申请的签名名称
        request.putQueryParameter("TemplateCode", "SMS_193524670");// 阿里云中申请的模板Code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        // 最终发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
            throw new GuliException(20001, "验证码发送异常...");
        }
    }

    @Override
    public String getCodeFromRedis(String key) {
        String code = redisTemplate.opsForValue().get(key);
        return code;
    }

    @Override
    public void setCodeToRedis(String key, String value, int time, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, time, timeUnit);
    }
}
